package com.itheima.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.entity.Comment;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.CommentMapper;
import com.itheima.service.CommentService;
import com.itheima.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service //交给spring容器
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<Comment> findListByMovieId(Integer movieId) {
        return commentMapper.findListByMovieId(movieId);
    }

    @Override
    public void save(Comment comment) {
        //完善数据
        comment.setTime(new Date());
        comment.setCreatorName("匿名");

        commentMapper.save(comment);
    }

    @Override
    public PageInfo findByPage(Integer pageNum, Integer pageSize, String creatorName, String moviesTitle) {
        //1.参数校验
        if (pageNum<=0) {
            pageNum=1;
        }
        if (pageSize<=0) {
            pageSize=5;
        }

        //2.使用pageHelper完成分页查询
        //- PageHelper.startPage(当前页码,每页条数);
        PageHelper.startPage(pageNum,pageSize);

        //- 紧跟着调用mapper查询数据库(这条语句就会自动分页),返回list
        //trim:去掉字符串两端空白 "  沈 腾 "==>"沈 腾"      "    "==>""
        creatorName = (creatorName==null?null:creatorName.trim());
        List<CommentVO> list = commentMapper.findList(creatorName,moviesTitle);

        //- 使用PageInfo构造器封装list,就可以获取总记录数和分页的一些其他参数
        return new PageInfo(list);
    }

    @Override
    public void deleteById(Integer id){
        commentMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(Integer[] ids) {
        //if (ids==null || ids.length==0) {
        if(ArrayUtil.isEmpty(ids)){
            //代码运行时遇到了异常,就不往下执行了;除非有异常的代码使用了try--catch机制,这样的话catch中的代码就会执行且还会往后继续执行
            throw new BusinessException("请选择要删除的评论");
        }

        commentMapper.deleteBatch(ids);
    }

    @Override
    public void deleteBatchByMoviesIds(Integer[] ids) {
        if (ArrayUtil.isEmpty(ids)) {
            throw new BusinessException("请选择要删除的影视");
        }

        commentMapper.deleteBatchByMoviesIds(ids);
    }
}
